import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import returnInApi from '@/api/in/returnIn-api'
import requirementApi from '@/api/purchase/requirement-api'
import projectApi from '@/api/inwarehouse/project-api'
import goodsApi from '@/api/inwarehouse/goods-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const statusOptions = [
      { value: '0', label: '新增' },
      { value: '99', label: '已完成' },
      // { value: '100', label: '已同步' }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '退货入库单',
      api: returnInApi,
      columns: [
        { prop: 'projectName', label: '项目', valueType: 'input' },
        { prop: 'createOn', label: '日期', slot: true, width: 120 },
        { prop: 'status', label: '状态', valueType: 'select', options: statusOptions, slot: true, width: 100 },
        { prop: 'operation', label: '操作', slot: true, width: 150 }
      ],
      rules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        // requirement: [{ required: true, message: '请选择产品', trigger: 'change' }],
      },
      other: {
        async finish(row) {
          // const data = row
          // console.log(data)
          row['status'] = '99';
          const res = await returnInApi.save(row)
          if(res.code === 200) {
            data.dialogVisible = false
            ElMessage.success('退货单完成')
            ctx.loadData()
          }
        },
        add() {
          const arr = ctx.editData['goodsList'].filter(item => {
            return item.number !== '' && item.number > 0
          })
          if(!arr || arr.length === 0 ) {
            ElMessage.error('暂无退货物料');
            return
          }
          ctx.editData['orderGoodsList'] = arr;
          ctx.save()
        },
        async detail(row) {
          ctx.editLoading = true
          const res = await returnInApi.detail(row.id)
          ctx.editLoading = false
          ctx.editData = res.data
          data.records = res.data.orderGoodsList
          data.dialogVisible = true
        },
        formatDt(val) {
          if(!val) {
            return '-'
          }
          return val.substring(0, 10)
        },
        getStatusName(val: string) {
          const obj = statusOptions.find(item => {
            return item.value === val
          })
          if (obj) {
            return obj['label']
          }
          return '-'
        },
        handleProjectChange(val: string) {
          const obj = data.projectOptions.find(item => {
            return item.id === val
          })
          ctx.editData['projectName'] = obj.name
          ctx.editData['projectOriginalNo'] = obj.originalNo
          ctx.editData['status'] = '0'
          getRequirementList(val)
        },
        addGoods() {
          if(!ctx.editData['goodsList']) {
            ctx.editData['goodsList'] = []
          }
          ctx.editData['goodsList'].push({})
        },
        delGoods() {
          data.delGoodsList.map(dgl => {
            const index = ctx.editData['goodsList'].findIndex(item => {
              return item.id ===  dgl.id
            })
            ctx.editData['goodsList'].splice(index, 1)
          })
        },
        handleGoodsSelectionChange(val: any) {
          if(!ctx.editData['goodsList']) {
            return
          }
          data.delGoodsList = val
        },
        handleGoodsChange(val: string) {
          const obj = data.goodsOptions.find(item => {
            return item.skuName === val
          })
          const index = ctx.editData['goodsList'].findIndex(item => {
            return item.skuName === val
          })
          obj['number1'] = obj['number']
          ctx.editData['goodsList'].splice(index, 1, obj)
        },
        async handleRequirementChange(val) {
          const temp = data.requirementOptions.find(item => {
            return val === item.id
          })
          ctx.editData['locationCode'] = temp.locationCode
          ctx.editData['status'] = '0'
          let arr = []
          const res = await requirementApi.detail(val)
          if(res.data) {
            const orderGoodsList = res.data.orderGoodsList
            orderGoodsList.map(item => {
              const obj = {...item}
              obj['number'] = ''
              obj['goodsId'] = obj['id']
              delete obj['id']
              arr.push(obj)
            })
            ctx.editData['goodsList'] = arr
          }
          console.log(ctx.editData)
        }
      }
    }))

    const getRequirementList = async (projectId) => {
      const params = { filter: { projectId } }
      const res = await requirementApi.list(params)
      data.requirementOptions = res.data.records
    }

    const getProjectList = async () => {
      const params = { filter: { disabled: 2 } }
      const res = await projectApi.list(params)
      data.projectOptions = res.data.records
    }

    const getGoodsList =  async () => {
      data.getGoodsLoading = true
      const res = await goodsApi.list()
      data.getGoodsLoading = false
      data.goodsOptions = res.data.records
    }


    const data = reactive({
      ctx,
      requirementOptions: [],
      projectOptions: [],
      goodsOptions: [],
      getGoodsLoading: false,
      delGoodsList: [],
      number: 1,
      records: [],
      dialogVisible: false
    })

    watch(() => data.number, (newVal, oldVal) => {
      if(!newVal) {
        return
      }
      if(ctx.editData.goodsList) {
        ctx.editData.goodsList.map(item => {
          item['number'] = item['number1'] * newVal
        })
      }
    })

    // init
    onMounted(() => {
      getProjectList()
      getGoodsList()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
